package net.huashitong.Indicators.app;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Indicators.dataBean.MyInfoDataBean;
import net.huashitong.Indicators.dataBean.MyInfoDetailDataBean;
import net.huashitong.Indicators.entity.AppMessage;
import net.huashitong.Indicators.entity.UserInfo;
import net.huashitong.Indicators.filter.AppMessageFilter;
import net.huashitong.Indicators.filter.UserInfoFilter;
import net.huashitong.Indicators.service.AppMessageService;
import net.huashitong.Indicators.service.UserInfoService;
import net.huashitong.Indicators.utils.DateForIndUtils;
import net.huashitong.until.Until;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 我的消息
 */
@Controller
@RequestMapping(value = "app/myinfo")
public class MyInfoController extends JsonBaseController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private AppMessageService appMessageService;

    @Override
    protected String getView(String s) {
        return null;
    }

    /**
     * 获取消息列表
     *
     * @param filter openId、token
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getmyinfo", method = RequestMethod.POST)
    public Message getMyInfo(@RequestBody UserInfoFilter filter) {
        //不需要传token
        String sysId = filter.getOpenId();
        List<MyInfoDataBean> result = new ArrayList<>();
        AppMessageFilter appMessageFilter = new AppMessageFilter();
        appMessageFilter.setReceiver(sysId);
        List<AppMessage> appMsgs = appMessageService.queryByUserIdOrderCreateDate(appMessageFilter);
        for (AppMessage msg : appMsgs) {
            MyInfoDataBean myInfoDataBean = new MyInfoDataBean();
            myInfoDataBean.setCtitle(msg.getMsgTitle());
            myInfoDataBean.setDatasource(msg.getSource());
            myInfoDataBean.setInfoid(msg.getSysId());
            myInfoDataBean.setInfostate(msg.getReadStatus());
            myInfoDataBean.setPushtime(msg.getCreateDate() + " " + msg.getCreateTime());
            myInfoDataBean.setUserid(msg.getSender());
            myInfoDataBean.setPicture(ObjectUtils.isBlank(msg.getPicture())?"-":msg.getPicture());
            myInfoDataBean.setMyInfoFlag("2");
            if (msg.getMsgText().length() >= 40) {
                myInfoDataBean.setContentOutline(msg.getMsgText().substring(0, 40));
            } else {
                myInfoDataBean.setContentOutline(msg.getMsgText());
            }
            result.add(myInfoDataBean);
        }

        UserInfo userInfo = userInfoService.getById(sysId);
        String user = userInfo.getUserId();
        String url = "user=" + user;
        String myInfos = null;
        try {
            myInfos = Until.HttpGET(Until.GET_MYINFO + url, 5000, 5000);
        } catch (IOException e) {
            logger.info("接口：" + Until.GET_MYINFO + url);
            return coverMessage("200", "获取消息列表成功", result);
        }
        if (StringUtils.isBlank(myInfos)) {
            return coverMessage("200", "获取消息列表失败");
        }
        JSONArray jsonArray = JSONObject.parseArray(myInfos);
        if (jsonArray.size() > 0) {
            for (java.util.Iterator tor = jsonArray.iterator(); tor.hasNext(); ) {
                MyInfoDataBean myInfoDataBean = new MyInfoDataBean();
                JSONObject job = (JSONObject) tor.next();
                String pushTime = job.getString("pushtime");    //pushTime精确到毫秒
                String timeRes = DateForIndUtils.timeStamp2Date(pushTime.substring(0, 10), "yyyy-MM-dd HH:mm:ss");
                job.put("pushtime", timeRes);
                myInfoDataBean.setCtitle(job.get("ctitle").toString());
                myInfoDataBean.setDatasource(job.get("datasource").toString());
                myInfoDataBean.setInfoid(job.get("infoid").toString());
                myInfoDataBean.setInfostate(job.get("infostate").toString());
                myInfoDataBean.setPushtime(job.get("pushtime").toString());
                myInfoDataBean.setUserid(job.get("userid").toString());
                myInfoDataBean.setMyInfoFlag("1");
                myInfoDataBean.setPicture("-");
                myInfoDataBean.setContentOutline("");
                result.add(myInfoDataBean);
            }
        }
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Collections.sort(result, new Comparator<MyInfoDataBean>() {
            @Override
            public int compare(MyInfoDataBean o1, MyInfoDataBean o2) {
                try {
                    long v1 = sdf.parse(o1.getPushtime()).getTime() / 1000;
                    long v2 = sdf.parse(o2.getPushtime()).getTime() / 1000;
                    if (v1 < v2) {
                        return 1;
                    } else if (v1 > v2) {
                        return -1;
                    } else {
                        return 0;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });

        return coverMessage("200", "获取消息列表成功", result);
    }

    /**
     * 获取单条消息
     *
     * @param filter userId、code(token)、openId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getoneinfo", method = RequestMethod.POST)
    public Message getOneInfo(@RequestBody UserInfoFilter filter) {
        //不需要传token
        String sysId = filter.getOpenId();
        UserInfo userInfo = userInfoService.getById(sysId);
        String code = filter.getCode();

        MyInfoDetailDataBean detailDataBean = new MyInfoDetailDataBean();
        //华通人接口
        if ("1".equals(filter.getMyInfoFlag())) {
            String url = "code=" + code;
            String oneInfo = null;
            try {
                oneInfo = Until.HttpGET(Until.GET_ONE_INFO + url, 5000, 5000);
            } catch (IOException e) {
                e.printStackTrace();
                logger.info("接口：" + Until.GET_ONE_INFO + url);
            }
            if (StringUtils.isBlank(oneInfo)) {
                return coverMessage("500", "获取单条消息失败");
            }
            JSONObject jsonArray = JSONObject.parseObject(oneInfo);
            if (jsonArray != null) {
                String createtime = jsonArray.getString("createtime");
                String createtimeRes = DateForIndUtils.timeStamp2Date(createtime.substring(0, 10), "yyyy-MM-dd HH:mm:ss");
                jsonArray.put("createtime", createtimeRes.replace("-", ".").substring(0, 10));

                String updatetime = jsonArray.getString("updatetime");
                String updatetimeRes = DateForIndUtils.timeStamp2Date(updatetime.substring(0, 10), "yyyy-MM-dd HH:mm:ss");
                jsonArray.put("updatetime", updatetimeRes.replace("-", ".").substring(0, 10));

                detailDataBean.setCode(jsonArray.get("code").toString());
                detailDataBean.setCreatetime(jsonArray.get("createtime").toString());
                detailDataBean.setCtitle(jsonArray.get("ctitle").toString());
                detailDataBean.setDatasource(jsonArray.get("datasource").toString());
                detailDataBean.setEditor(jsonArray.get("editor").toString());
                detailDataBean.setInfocontent(jsonArray.get("infocontent").toString());
                detailDataBean.setState(jsonArray.get("state").toString());
                detailDataBean.setUpdatetime(jsonArray.get("updatetime").toString());
                detailDataBean.setPicture("-");
            }
            //调用单条消息时设置已读
            String userid = userInfo.getUserId();
            String lookInfoUrl = "infocode=" + code + "&userid=" + userid;
            //设置消息已读
            String lookInfo = null;
            try {
                lookInfo = Until.HttpGET(Until.LOOK_INFO + lookInfoUrl, 5000, 5000);
            } catch (IOException e) {
                logger.info("接口：" + Until.LOOK_INFO + lookInfoUrl);
                e.printStackTrace();
            }
            if (StringUtils.isBlank(lookInfo)) {
                return coverMessage("500", "设置已读消息失败");
            }
            JSONObject jsonObject = JSONObject.parseObject(lookInfo);
            if ("200".equals(jsonObject.getString("returncode"))) {
                return coverMessage("200", "获取单条消息成功", jsonArray);
            } else {
                return coverMessage("500", "获取单条消息成功但是调用已读接口出错", jsonArray);
            }
        } else if ("2".equals(filter.getMyInfoFlag())) {             //app端
            AppMessage appMessage = appMessageService.getById(code);
            //设置已读
            appMessage.setReadStatus("1");
            appMessageService.update(appMessage);
            detailDataBean.setCode(appMessage.getSysId());
            detailDataBean.setCreatetime(appMessage.getCreateDate() + " " + appMessage.getCreateTime());
            detailDataBean.setCtitle(appMessage.getMsgTitle());
            detailDataBean.setDatasource(appMessage.getSource());
            detailDataBean.setEditor(appMessage.getSource());
            detailDataBean.setInfocontent(appMessage.getMsgText());
            detailDataBean.setState(appMessage.getReadStatus());
            detailDataBean.setUpdatetime(appMessage.getUpdDate() + " " + appMessage.getUpdTime());
            detailDataBean.setPicture(ObjectUtils.isBlank(appMessage.getPicture())?"-":appMessage.getPicture());
            return coverMessage("200", "获取单条消息成功", detailDataBean);
        } else {
            return coverMessage("200", "缺少参数：消息接口来源");
        }
    }

    /**
     * 删除我的消息
     *
     * @param filter infocode、openId、token
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deletemyinfo", method = RequestMethod.POST)
    public Message deleteMyInfo(@RequestBody UserInfoFilter filter) {

        //不需要传token
        String sysId = filter.getOpenId();
        String infocode = filter.getInfoCode();

        //华通人接口
        if ("1".equals(filter.getMyInfoFlag())) {
            UserInfo userid = userInfoService.getById(sysId);
            String url = "infocode=" + infocode + "&userid=" + userid;
            String deletInfo = null;
            try {
                deletInfo = Until.HttpGET(Until.DELETE_INFO + url, 5000, 5000);
            } catch (IOException e) {
                logger.info("接口：" + Until.DELETE_INFO + url);
                e.printStackTrace();
            }
            if (StringUtils.isBlank(deletInfo)) {
                return coverMessage("500", "删除消息失败");
            }
            JSONObject jsonObject = JSONObject.parseObject(deletInfo);
            if ("200".equals(jsonObject.getString("returncode"))) {
                return coverMessage("200", "删除消息成功");
            } else {
                return coverMessage("500", "删除消息失败");
            }
        } else if ("2".equals(filter.getMyInfoFlag())) {
            //政信云接口
            appMessageService.deleteById(infocode);
            return coverMessage("200", "删除消息成功");
        } else {
            return coverMessage("200", "缺少参数：消息接口来源");
        }
    }


    /**
     * 消息已读     (接口取消)
     *
     * @param filter userId、infocode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/lookinfo", method = RequestMethod.POST)
    public Message lookInfo(@RequestBody UserInfoFilter filter) {

        //不需要传token
        String infocode = filter.getInfoCode();
        String userid = filter.getUserId();
        String url = "infocode=" + infocode + "&userid=" + userid;
        String lookInfo = null;
        try {
            lookInfo = Until.HttpGET(Until.LOOK_INFO + url, 5000, 5000);
        } catch (IOException e) {
            logger.info("接口：" + Until.LOOK_INFO + url);

            e.printStackTrace();
        }
        if (StringUtils.isBlank(lookInfo)) {
            return coverMessage("500", "消息已读失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(lookInfo);
        if ("200".equals(jsonObject.getString("returncode"))) {
            return coverMessage("200", "消息已读成功");
        } else {
            return coverMessage("500", "消息已读失败");
        }
    }


    /**
     * 通过userId 获取最新的token并返回结果
     *
     * @param userId
     * @return
     */
    public JSONArray getMyInfoByUserId(String userId) {
        String pwd = userInfoService.getPwdByUser(userId);
        //调用接口获取新的token
        String newToken = userInfoService.getToken(userId, pwd);
        String newUrl = "user=" + userId + "&token=" + newToken;
        String newMyInfos = null;
        try {
            newMyInfos = Until.HttpGET(Until.GET_MYINFO_NEED_TOKEN + newUrl, 5000, 5000);
        } catch (IOException e) {
            logger.info("接口：" + Until.GET_MYINFO_NEED_TOKEN + newUrl);
            e.printStackTrace();
        }
        if (StringUtils.isBlank(newMyInfos)) {
            return null;
        }
        JSONObject newJsonObject = JSONObject.parseObject(newMyInfos);
        JSONArray result = newJsonObject.getJSONArray("returndata");
        if (result.size() > 0) {
            for (java.util.Iterator tor = result.iterator(); tor.hasNext(); ) {
                JSONObject job = (JSONObject) tor.next();
                String pushTime = job.getString("pushtime");    //pushTime精确到毫秒
                String timeRes = DateForIndUtils.timeStamp2Date(pushTime.substring(0, 10), "yyyy-MM-dd HH:mm:ss");
                job.put("pushtime", timeRes.replace("-", ".").substring(0, 10));
            }
        }
        return result;
    }

    /**
     * 通过userId、code 获取最新的token并返回结果
     *
     * @param userInfo
     * @return
     */
    public JSONArray getOneInfoByUserId(UserInfo userInfo, String code) {
        String pwd = userInfo.getPwd();
        String userId = userInfo.getUserId();
        //调用接口获取新的token
        String newToken = userInfoService.getToken(userId, pwd);
        userInfo.setToken(newToken);
        userInfoService.update(userInfo);
        String newUrl = "code=" + code + "&token=" + newToken;
        String newOneInfos = null;
        try {
            newOneInfos = Until.HttpGET(Until.GET_ONE_INFO_NEED_TOKEN + newUrl, 5000, 5000);
        } catch (IOException e) {
            logger.info("接口：" + Until.GET_ONE_INFO_NEED_TOKEN + newUrl);
            e.printStackTrace();
        }
        if (StringUtils.isBlank(newOneInfos)) {
            return null;
        }
        JSONObject newJsonObject = JSONObject.parseObject(newOneInfos);
        JSONArray result = newJsonObject.getJSONArray("returndata");
        return result;
    }

    /**
     * 通过userId、infocode 获取最新的token并返回结果
     * （不使用）
     *
     * @param userInfo
     * @param infocode
     * @return
     */
    public String deleteMyInfo(UserInfo userInfo, String infocode) {
        String pwd = userInfo.getPwd();
        String userId = userInfo.getUserId();
        //调用接口获取新的token
        String newToken = userInfoService.getToken(userId, pwd);
        userInfo.setToken(newToken);
        userInfoService.update(userInfo);
        String newUrl = "infocode=" + infocode + "&userId=" + userId + "&token=" + newToken;
        String newOneInfos = null;
        try {
            newOneInfos = Until.HttpGET(Until.DELETE_INFO_NEED_TOKEN + newUrl, 5000, 5000);
        } catch (IOException e) {
            logger.info("接口：" + Until.DELETE_INFO_NEED_TOKEN + newUrl);
            e.printStackTrace();
        }
        if (StringUtils.isBlank(newOneInfos)) {
            return null;
        }
        JSONObject newJsonObject = JSONObject.parseObject(newOneInfos);
        String result = newJsonObject.getString("returncode");
        return result;
    }

    /**
     * 通过userId、infocode 获取最新的token并返回结果
     *
     * @param userInfo
     * @param infocode
     * @return
     */
    public String lookInfo(UserInfo userInfo, String infocode) {
        String pwd = userInfo.getPwd();
        String userId = userInfo.getUserId();
        //调用接口获取新的token
        String newToken = userInfoService.getToken(userId, pwd);
        userInfo.setToken(newToken);
        userInfoService.update(userInfo);
        String newUrl = "infocode=" + infocode + "&userid=" + userId + "&token=" + newToken;
        String newLookInfos = null;
        try {
            newLookInfos = Until.HttpGET(Until.LOOK_INFO_NEED_TOKEN + newUrl, 5000, 5000);
        } catch (IOException e) {
            logger.info("jiekou :" + Until.LOOK_INFO_NEED_TOKEN + newUrl);
            e.printStackTrace();
        }
        if (StringUtils.isBlank(newLookInfos)) {
            return null;
        }
        JSONObject newJsonObject = JSONObject.parseObject(newLookInfos);
        String result = newJsonObject.getString("returncode");
        return result;
    }
}
